import { BaseChannel } from "../../core/channel/BaseChannel";
import { registerClass } from "../../../cfw/tools/class_decorator";
import { ADName, SDKState } from "../../SDKDefine";
import { BaseAdMgr } from "../../core/base/BaseAdMgr";
import { GMRewardAd } from "./GMRewardAd";
/**
 * https://gamedistribution.com/developers/sdk/cocos/
 */
@registerClass('GMChannel')
export class GMChannel extends BaseChannel {



    initPlatform() {

        window["SDK_OPTIONS"] = {
            "gameId": this.data.gameId,
            "onEvent": (event: any) => {

                console.log(' window["SDK_OPTIONS"] ', event.name)
                switch (event.name) {
                    case "SDK_GAME_START":// advertisement done, resume game logic and unmute audio
                        break;
                    case "SDK_GAME_PAUSE":
                        // pause game logic /mute audio
                        break;
                    case "SDK_GDPR_TRACKING":
                        // this event is triggered when your user doesn't want to be tracked
                        break;
                    case "SDK_GDPR_TARGETING":
                        // this event is triggered when your user doesn't want personalised targeting of ads and such
                        break;
                    case "COMPLETE":
                        // this event is triggered when your user completely watched rewarded ad
                        this.onVideoComplete();
                        break;
                    case "AD_ERROR":
                        this.onAdError()
                        break;
                    case "SDK_READY":
                        break;

                }
            }
        };


        (function (a: any, b, c) {
            var d = a.getElementsByTagName(b)[0];
            a.getElementById(c) || (a = a.createElement(b), a.id = c, a.src = "https://api.gamemonetize.com/sdk.js", d.parentNode.insertBefore(a, d))
        })(document, "script", "gamemonetize-sdk");
    }


    onVideoComplete() {
        let adMgr: BaseAdMgr = this.getAd(ADName.reward)
        let ad: GMRewardAd = adMgr.get() as GMRewardAd;
        if (ad) {
            ad.onClose({ isEnded: true })
        }
    }

    onAdError() {
        let adMgr: BaseAdMgr = this.getAd(ADName.reward)
        let ad: GMRewardAd = adMgr.get() as GMRewardAd;
        if (ad && ad.isState(SDKState.show)) {
            ad.onError('ad error')
        }
    }


}